package com.shangyueshang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shangyueshang.common.SysConstants;
import com.shangyueshang.mapper.ProductMapper;
import com.shangyueshang.model.Product;
import com.shangyueshang.request.PageReq;
import com.shangyueshang.request.ProductDTO;
import com.shangyueshang.response.HttpResult;
import com.shangyueshang.response.PageResult;
import com.shangyueshang.service.ProductService;
import com.shangyueshang.utils.MyPageHelper;
import com.shangyueshang.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author JokeyFeng
 * @date: 2022/1/15 23:00
 * @project: shangyueshang
 * @package: com.shangyueshang.service.impl
 * @comment:
 */
@Slf4j
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Override
    public PageResult<Product> findPage(PageReq pageReq) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc(SysConstants.create_time);
        Map<String, Object> queryParams = pageReq.getLineParams();
        queryParams.forEach((k, v) -> {
            if (k.equals(SysConstants.name)) {
                queryWrapper.like(k, v);
            } else if (k.equals(SysConstants.supplier_ids)) {
                queryWrapper.like(k, v);
            } else {
                queryWrapper.eq(k, v);
            }
        });
        PageInfo<Product> pageInfo =
                PageHelper.startPage(
                        pageReq.getPageNum(),
                        pageReq.getPageSize()
                ).doSelectPageInfo(() -> super.list(queryWrapper));
        return MyPageHelper.getPageResult(pageInfo);
    }

    @Override
    public HttpResult<Boolean> saveUpdate(ProductDTO dto) {
        Product product = super.getOne(new QueryWrapper<Product>().eq(SysConstants.inner_code, dto.getInnerCode()));
        if (product == null) {
            product = new Product();
            product.setCreator(SecurityUtil.getUsername());
        }
        product.setLastUpdator(SecurityUtil.getUsername());
        BeanUtils.copyProperties(dto, product);
        return HttpResult.ok(super.saveOrUpdate(product));
    }
}
